﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Management;
using BaseHelper.Encrypt;
using System.Runtime.InteropServices;

namespace BaseHelper.Base
{
    public class SysHelper
    {
        [DllImportAttribute("Kernel32.dll")]

        public static extern void GetLocalTime(SystemTime st);

        [DllImportAttribute("Kernel32.dll")]

        public static extern void SetLocalTime(SystemTime st);

        [StructLayoutAttribute(LayoutKind.Sequential)]
        public class SystemTime
        {

            public ushort vYear;

            public ushort vMonth;

            public ushort vDayOfWeek;

            public ushort vDay;

            public ushort vHour;

            public ushort vMinute;

            public ushort vSecond;

        }
    


        public static void Sleep(int millisecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) <= millisecond)
                Application.DoEvents();
        }
        public static string AppPath
        {
            get{
                return AppDomain.CurrentDomain.BaseDirectory;// Environment.CurrentDirectory;
            }
        }

        public static void Set_IE10()
        {
            //设置IE内核为 IE10
            string regPath32 = @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION";
            string regPath64 = @"SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION";
            string zoom = @"Software\Microsoft\Internet Explorer\Zoom";

            string value = "10001"; //9999 
            try
            {
                RegistryKey reg = Registry.LocalMachine.OpenSubKey(regPath32, true);
                reg.SetValue(Path.GetFileName(Application.ExecutablePath), value, RegistryValueKind.DWord);
                reg.SetValue(Path.GetFileName(Application.ExecutablePath.Replace(".EXE", ".vshost.exe")), value, RegistryValueKind.DWord);
                reg.Close();
            }
            catch { }

            try
            {
                RegistryKey reg = Registry.LocalMachine.OpenSubKey(regPath64, true);
                reg.SetValue(Path.GetFileName(Application.ExecutablePath), "10001  ", RegistryValueKind.DWord);
                reg.SetValue(Path.GetFileName(Application.ExecutablePath.Replace(".EXE", ".vshost.exe")), value, RegistryValueKind.DWord);
                reg.Close();
            }
            catch { }

            try
            {
                RegistryKey reg = Registry.CurrentUser.OpenSubKey(zoom, true);
                reg.SetValue("ZoomDisabled", "1  ", RegistryValueKind.DWord);
                reg.Close();
            }
            catch { }
        }

        public static string GetMachineID()
        {
         
            //GetMacAddress() + 
            string temp =  GetDiskID() + GetCpuID() + GetPhisicalMemory().ToString() + GetDiskSize();
            return Md5Helper.Encrypt(temp);
        }

        private static int GetPhisicalMemory()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher();   //用于查询一些如系统信息的管理对象 
            searcher.Query = new SelectQuery("Win32_PhysicalMemory ", "", new string[] { "Capacity" });//设置查询条件 
            ManagementObjectCollection collection = searcher.Get();   //获取内存容量 
            ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();

            long capacity = 0;
            while (em.MoveNext())
            {
                ManagementBaseObject baseObj = em.Current;
                if (baseObj.Properties["Capacity"].Value != null)
                {
                    try
                    {
                        capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString());
                    }
                    catch
                    {
                        return 0;
                    }
                }
            }
            return (int)(capacity / 1024 / 1024);
        }

        public static string GetMacAddress()
        {
        
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc2 = mc.GetInstances();
            foreach (ManagementObject mo in moc2)
            {
                if ((bool)mo["IPEnabled"] == true)
                    return mo["MacAddress"].ToString().ToLower();
                mo.Dispose();
            }

            return "";
        }

        private static string GetDiskID()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
            disk.Get();
            return disk.GetPropertyValue("VolumeSerialNumber").ToString();
        }

        private static string GetCpuID()
        {
            string strCpu = "0000";
            try
            {
                ManagementClass myCpu = new ManagementClass("win32_Processor");
                ManagementObjectCollection myCpuConnection = myCpu.GetInstances();
                foreach (ManagementObject myObject in myCpuConnection)
                {
                    strCpu = myObject.Properties["Processorid"].Value.ToString().ToLower();
                    break;
                }
                myCpuConnection.Dispose();
                myCpu.Dispose();
            }
            catch { };
            return strCpu;
        }

        private static long GetDiskSize()
        {
            DriveInfo[] ds = DriveInfo.GetDrives();
            long sizetotal = 0;
            foreach (DriveInfo d in ds)
            {
                if (d.IsReady)
                    if (d.DriveType == DriveType.Fixed)
                        sizetotal += d.TotalSize;
            }
            return sizetotal;
        }

        public static bool IsVistualMachine()
        {
            bool ret = false;
            string mac = GetMacAddress().ToLower().Replace(":", "");
            if (mac.Contains("000c29") || mac.Contains("001c14") || mac.Contains("005056") || mac.Contains("080027"))
                ret = true;
            return ret;
        }


        public static void SetLocalTime(string timestamp,int fixSecond=0)
        {
            if (timestamp == "")
                return;
            try
            {
                DateTime dt = TimeHelper.ToDateTime(timestamp).AddSeconds(fixSecond);
                SetLocalTime(dt);
            }
            catch (Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.SysHelper.cs", "SetLocalTime()", ex);
            }
        
        }
        public static void SetLocalTime(DateTime dt)
        {
            try
            {
                SystemTime st = new SystemTime();
                st.vYear = (ushort)dt.Year;

                st.vMonth = (ushort)dt.Month;

                st.vDay = (ushort)dt.Day;

                st.vHour = (ushort)dt.Hour;

                st.vMinute = (ushort)dt.Minute;

                st.vSecond = (ushort)dt.Second;

                SetLocalTime(st);
            }
            catch (Exception ex)
            {
                LogHelper.Err("BaseHelper.Base.SysHelper.cs", "SetLocalTime()", ex);
            }
        }


    }

}
